package pl.matt.dao.impl;

import java.util.Collection;

import org.hibernate.Criteria;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import pl.matt.dao.AbstractEntityDao;
import pl.matt.model.AbstractEntity;

public class HibernateAbstractEntityDao<T extends AbstractEntity> extends HibernateDaoSupport implements AbstractEntityDao<T> {

	private Class<T> entityClass;
	
	protected HibernateAbstractEntityDao(Class<T> entityClass) {
		this.entityClass = entityClass;
	}
	
	protected Class<T> getEntityClass() {
		return entityClass;
	}
	
	@Override
	public void create(T object) {
		getHibernateTemplate().save(object);		
	}

	@Override
	public void createOrUpdate(T object) {
		getHibernateTemplate().saveOrUpdate(object);		
	}

	@Override
	public void delete(T object) {
		getHibernateTemplate().delete(object);		
	}

	@SuppressWarnings("unchecked")
	@Override
	public T read(Long id) {
		return (T) getHibernateTemplate().get(entityClass, id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Collection<T> readAll() {
		return getHibernateTemplate().loadAll(entityClass);
	}

	@Override
	public void update(T object) {
		getHibernateTemplate().update(object);		
	}

	protected Criteria createCriteria() {
		return getSession().createCriteria(entityClass);
	}

	@Override
	public void create(Collection<T> collection) {
		for (T t : collection) {
			create(t);
		}		
	}

	@Override
	public void createOrUpdate(Collection<T> collection) {
		getHibernateTemplate().saveOrUpdateAll(collection);		
	}

	@Override
	public void update(Collection<T> collection) {
		if (collection != null) {
			for (T t : collection) {
				update(t);
			}
		}
	}
	
}
